package com.acwing.lc.part1;

/**
 * @author rkc
 * @date 2022/9/16 14:52
 */
public class LC59螺旋矩阵II {

    private final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    private boolean[][] st = new boolean[20][20];

    public int[][] generateMatrix(int n) {
        int[][] ans = new int[n][n];
        for (int i = 1, x = 0, y = 0, d = 0; i <= n * n; i++) {
            ans[x][y] = i;
            st[x][y] = true;
            int nx = x + dirs[d][0], ny = y + dirs[d][1];
            if (nx < 0 || nx >= n || ny < 0 || ny >= n || st[nx][ny]) {
                d = (d + 1) % 4;
                nx = x + dirs[d][0];
                ny = y + dirs[d][1];
            }
            x = nx;
            y = ny;
        }
        return ans;
    }
}
